package com.xindaoapp.happypet.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.XDHttpClient;
import com.xindaoapp.happypet.activity.HomeBannerDetailActivity;
import com.xindaoapp.happypet.adapter.HomeVideoAdapter;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.HomeBanner;
import com.xindaoapp.happypet.bean.HomeBannerEntity;
import com.xindaoapp.happypet.bean.HomeVideo;
import com.xindaoapp.happypet.bean.HomeVideo.Video;
import com.xindaoapp.happypet.ui.PostDetailActivity;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.xdConfig;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshListView;

public class Club_VideoFragement extends XDBaseFragment {
    private static Context context;
    private static Club_VideoFragement j;
    private PullToRefreshListView list;
    private int videopage = 1;

    /** 返回顶部 */
    private View mBackToTop;

    public static Club_VideoFragement getInstance(Context context1) {
        j = new Club_VideoFragement();
        context = context1;
        return j;
    }

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    videoPager.setCurrentItem(videoPager.getCurrentItem() + 1);
                    break;
                default:
                    break;
            }
        }
    };

    // private SharedPreferences userconfig;
    // private boolean wifi;
    @Override
    public void onResume() {
        // wifi=userconfig.getBoolean("wifi", true);
        super.onResume();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return mView = inflater.inflate(R.layout.club_new, container, false);
    }


    private boolean isload = false;

    @Override
    protected void initUi() {
        loading.setVisibility(View.GONE);
        mBackToTop = getView().findViewById(R.id.back_top);

        mBackToTop.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                list.getRefreshableView().smoothScrollToPosition(0);
            }
        });

        list = (PullToRefreshListView) findViewById(R.id.list);
        getVideoBannerData(context);

        list.setPullRefreshEnabled(true);
        list.setScrollLoadEnabled(true);
        list.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (videos.size() > 0) {
                    videos.clear();
                }
                videopage = 1;
                loadVideoData(videopage);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (total == videos.size()) {
                    Toast.makeText(context, "没有更多数据了", Toast.LENGTH_SHORT).show();
                    onViewLoaded();
                } else {
                    videopage++;
                    loadVideoData(videopage);
                }
            }
        });
        list.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int newposition;
                if (list.getRefreshableView().getHeaderViewsCount() > 0) {
                    newposition = position - 1;
                } else {
                    newposition = position;
                }
                Intent intent = new Intent(context, PostDetailActivity.class);
                intent.putExtra(Constants.KEY_POST_TID, videos.get(newposition).tid);
                intent.putExtra(Constants.KEY_FROM_PAGE, 0);
                startActivity(intent);
            }
        });
        list.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                if (firstVisibleItem >= 10) {
                    mBackToTop.setVisibility(View.VISIBLE);
                } else {
                    mBackToTop.setVisibility(View.GONE);
                }
            }

        });
    }

    private List<HomeBanner> videoBanner;
    private LinearLayout videoL;
    private ViewPager videoPager;
    private int videopreviousSelectPosition = 0;
    private TextView videotvDescription;

    private void getVideoBannerData(final Context context) {
        if (CommonUtil.checkNetState(context)) {
            RequestParams params = new RequestParams();
            params.put("", "");
            XDHttpClient.get(xdConfig.HOME_BANNER, params, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, String content) {
                    if (!TextUtils.isEmpty(content)) {
                        HomeBannerEntity entity = null;
                        try {
                            entity = JSON.parseObject(content, HomeBannerEntity.class);
                        } catch (Exception e) {
                        }
                        videoBanner = entity.getArray();
                        View view = View.inflate(context, R.layout.main_new_banner, null);
                        videoPager = (ViewPager) view.findViewById(R.id.new_viewpager);
                        videotvDescription =
                                (TextView) view.findViewById(R.id.tv_image_description1);
                        videoL = (LinearLayout) view.findViewById(R.id.ll_points1);
                        prepareVideoViewPage(context, videoBanner);
                        if (!isload) {
                            loadVideoData(videopage);
                            isload = true;
                        }
                        if (list.getRefreshableView().getHeaderViewsCount() < 1) {
                            list.getRefreshableView().addHeaderView(view);
                        }
                    }
                }

                @Override
                public void onFinish() {
                    if (loading != null && loading.getVisibility() == View.VISIBLE) {
                        animation.stop();
                        loading.setVisibility(View.GONE);
                    }
                }

                @Override
                public void onFailure(Throwable arg0, String arg1) {
                    super.onFailure(arg0, arg1);
                    Toast.makeText(context, R.string.get_error_data, 0).show();
                }
            });
        } else {
            Toast.makeText(context, R.string.pLease_check_network, 0).show();
            return;
        }
    }

    public void prepareVideoViewPage(Context context, final List<HomeBanner> list) {
        prepareVideoData(context, list);
        ViewPagerVideoAdapter adapter = new ViewPagerVideoAdapter();
        videoPager.setAdapter(adapter);
        videoPager.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageSelected(final int position) {
                // 改变图片的描述信息
                videotvDescription.setText(list.get(position % list.size()).getTitle());
                // 切换选中的点
                videoL.getChildAt(videopreviousSelectPosition).setEnabled(false); // 把前一个点置为normal状态
                videoL.getChildAt(position % list.size()).setEnabled(true);// 把当前选中的position对应的点置为enabled状态
                videopreviousSelectPosition = position % list.size();
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {}

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {}
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    SystemClock.sleep(5000);
                    handler.sendEmptyMessage(1);
                }
            }
        }).start();
        videotvDescription.setText(list.get(videopreviousSelectPosition).getTitle());
        videoL.getChildAt(videopreviousSelectPosition).setEnabled(true);
    }

    private void prepareVideoData(Context context, List<HomeBanner> list) {
        // ImageView iv;
        View view;
        for (int i = 0; i < list.size(); i++) {
            // 添加点view对象
            view = new View(context);
            view.setBackgroundDrawable(context.getResources().getDrawable(
                    R.drawable.point_background));
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(15, 15);
            lp.leftMargin = 10;
            view.setLayoutParams(lp);
            view.setEnabled(false);
            videoL.addView(view);
        }
    }

    class ViewPagerVideoAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        /** 判断出去的view是否等于进来的view 如果为true直接复用 */
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        /** 销毁预加载以外的view对象, 会把需要销毁的对象的索引位置传进来就是position */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        /** 创建一个view */
        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView iv = new ImageView(context);
            iv.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,
                    android.view.ViewGroup.LayoutParams.FILL_PARENT));
            iv.setScaleType(ScaleType.FIT_XY);
            // if(wifi){
            // iv.setImageResource(R.drawable.lunbo_loading);
            // }else{
            // Picasso.with(context)
            // .load(videoBanner.get(position % videoBanner.size()).getCoverpath())
            // .placeholder(R.drawable.lunbo_loading).into(iv);
            // }
            container.addView(iv);
            final String type = videoBanner.get(position % videoBanner.size()).getType();
            iv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (type.equals("web")) {// 跳转到详情
                        Intent intent1 = new Intent(context, HomeBannerDetailActivity.class);
                        intent1.putExtra("url", videoBanner.get(position % videoBanner.size())
                                .getLink());
                        context.startActivity(intent1);
                    } else if (type.equals("appthread")) {// 跳转到帖子详情
                        Intent intent2 = new Intent(context, PostDetailActivity.class);
                        intent2.putExtra(Constants.KEY_POST_TID,
                                videoBanner.get(position % videoBanner.size()).getLink());
                        intent2.putExtra(Constants.KEY_FROM_PAGE, 0);
                        context.startActivity(intent2);
                    }
                }
            });
            return iv;
        }
    }

    private HomeVideoAdapter videoAdapter;
    private final List<HomeVideo.Video> videos = new ArrayList<HomeVideo.Video>();
    private int total;

    private void loadVideoData(int videopage2) {
        RequestParams params = new RequestParams();
        params.put("page", String.valueOf(videopage2));
        params.put("pagesize", Address.PAGESIZE);
        params.put("filter", "petvideo");
        // final ProgressHUD ProgressDialog = ProgressHUD.show(context, "正在加载...", true, true,
        // null);
        AddClient.get(Address.MAINNEW, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                try {
                    HomeVideo parse = JSON.parseObject(content, HomeVideo.class);
                    List<Video> array = parse.array;
                    if (array.size() > 0) {
                        videos.addAll(array);
                        // array.clear();
                    }
                    if (videoAdapter == null) {
                        videoAdapter = new HomeVideoAdapter(videos, context);
                        list.getRefreshableView().setAdapter(videoAdapter);
                    } else {
                        videoAdapter.notifyDataSetChanged();
                    }
                    total = Integer.parseInt(parse.getTotal());
                    onViewLoaded();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFinish() {
                if (loading != null && loading.getVisibility() == View.VISIBLE) {
                    animation.stop();
                    loading.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(Throwable error, String content) {
                Toast.makeText(context, "加载失败,请检查网络状态", Toast.LENGTH_SHORT).show();
                super.onFailure(error, content);
                onViewLoaded();
            }
        });
        setVideoUpdateTime();
    }

    private void onViewLoaded() {
        list.onPullDownRefreshComplete();
        list.onPullUpRefreshComplete();
    }

    /** 设置加载的时间 */
    private void setVideoUpdateTime() {
        String text = CommonUtil.formatPullToRefreshDate();
        list.setLastUpdatedLabel(text);
    }
}
